/* 项目配置 */
//导入模块
var express = require("express")
var path = require("path")
var cookieParser = require("cookie-parser")
var logger = require("morgan")
//导入require-directory模块
const AutoDir = require("require-directory")
//导入解决跨域模块
const cors = require("cors")

//配置函数
function initManage(app) {
  //注册插件
  /* 跨域中间件 */
  app.use(logger("dev"))
  app.use(express.json())
  app.use(express.urlencoded({ extended: false }))
  app.use(cookieParser())
  app.use(express.static(path.join(__dirname, "public")))
  //注册cors
  app.use(cors())
  const useRoutes = (obj) => {
    /* obj.stack为真就是一个路由 */
    if (obj.stack) {
      app.use(obj)
    }
  }
  AutoDir(module, "../routes", { visit: useRoutes })
  // 捕获404并转发到错误处理程序
  app.use(function (req, res, next) {
    next(createError(404))
  })
  // 错误处理程序
  app.use(function (err, req, res, next) {
    // 设置局部变量，仅在开发中提供错误
    res.locals.message = err.message
    res.locals.error = req.app.get("env") === "development" ? err : {}

    // 呈现错误页
    res.status(err.status || 500)
    res.render("error")
  })
}

module.exports = initManage
